<?php
namespace app\manage\model;
use app\manage\controller\ApartmentCost;
use think\Db;
use think\Model;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/8/5
 * Time: 16:25
 */
class ContracTmanagement extends Model
{

    /**
     * 类型房源选择
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function h_type($data){
      //  $data = input();
        //处理数据1是住房  2是商铺
        if($data['type']==1){
            $where['h_state']=1;
            $where['lease']=1;
            $where['create_id'] = create_id($data['token']);
            if($data['tung_num']!=null){
                $where['h_tung_num']=$data['tung_num'];//栋
                $where['h_unit_num']=$data['unit_num'];//单元
            }
            $data=Db::name('housing_information')
                ->field('housing_id,h_tung_num,h_unit_num,h_room_number,h_money,h_area,h_root,h_guest_room,h_toilet')
                ->where($where)
                ->order('h_tung_num asc,h_unit_num asc,h_room_number asc')
                ->select();
            if($data!=null){
                foreach($data as $k=>$v){
                    $data[$k]['unit']=$v['h_tung_num'].'-'.$v['h_unit_num'].'-'.$v['h_room_number'];
                    $data[$k]['apartment']=$v['h_root'].'室'.$v['h_guest_room'].'厅'.$v['h_toilet'].'卫';
                    $data[$k]['money']=$v['h_money'];
                    $data[$k]['h_id']=$v['housing_id'];
                    $data[$k]['area']=$v['h_area'];
                    $data[$k]['number']=$v['h_room_number'];
                }
            }
            return $data;
        }else{
            $where['s_state']=1;
            $where['lease']=1;
            $where['create_id'] = create_id($data['token']);
            if($data['tung_num']!=null){
                $where['s_tung_num']=$data['tung_num'];//栋
                $where['s_unit_num']=$data['unit_num'];//单元
            }
            $data=Db::name('shops')
                ->field('shops_id,s_tung_num,s_unit_num,s_room_number,s_money,s_area,s_face_width,s_layer_depth,s_depth')
                ->where($where)
                ->order('s_tung_num asc,s_unit_num asc,s_room_number asc')
                ->select();
            if($data!=null){
                foreach($data as $k=>$v){
                    $data[$k]['unit']=$v['s_tung_num'].'-'.$v['s_unit_num'].'-'.$v['s_room_number'];
                    $data[$k]['apartment']='面宽:'.$v['s_face_width'].'层深:'.$v['s_layer_depth'].'进深:'.$v['s_depth'];
                    $data[$k]['money']=$v['s_money'];
                    $data[$k]['h_id']=$v['shops_id'];
                    $data[$k]['area']=$v['s_area'];
                    $data[$k]['number']=$v['s_room_number'];
                }
            }
            return $data;
        }
    }
    /**
     * 选择添加合同默认选择住房房源
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function type(){
        //处理数据1是住房  2是商铺
        //单元楼数据
        $data = input();
        $where['create_id'] = create_id($data['token']);
        $data=Db::name('unit_building')
            ->field('tung_num,unit_num,layer_num')
            ->where($where)
            ->where(['u_type'=>1])
            ->order('tung_num asc,unit_num asc')
            ->select();
        if($data!=null){
            foreach($data as $k=>$v){
                $data[$k]['unit']=$v['tung_num'].'-'.$v['unit_num'];
            }
        }
        return $data;
    }

    /**
     * 根据手机号添加租客
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function phone($data){
        $data=Db::name('tenant_management')
            ->where(['tenant_tel'=>$data])
            ->field('tenant_id,tenant_name,tenant_tel,tenant_idcard')
            ->find();
        return $data;
    }
    /**
     * 根据手机号添加租客
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function phone2($data){
        $data=Db::name('tenant_management')
            ->where(['tenant_tel'=>$data])
            ->field('tenant_id,tenant_name,tenant_tel,tenant_idcard')
            ->select();
        return $data;
    }
    /**
     * 根据手机号添加租客
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function userPhone($data){
        $create_id=create_id($data['token']);
        $data=Db::name('tenant_management')
            ->where(['tenant_tel'=>$data['phone']])
            ->where(['create_id'=>$create_id])
            ->field('tenant_id,tenant_name,tenant_tel,tenant_idcard')
            ->find();
        return $data;
    }

    /**
     * 添加
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function TmanagementAdd($data){
        //添加操作用户id
        /*$uid=get_user_id($data['token']);
        $arr['te_uid'] = $uid;*/
        //var_dump($data);exit;
        $time=time();
        $e_time=strtotime(trim($data['c_d_time']))-10*24*60*60;
        if(strtotime(trim($data['c_d_time']))<$time){//逾期
            $arr['c_type']=3;
            $arr['c_state']=5;
        }elseif($e_time<$time){
            $arr['c_type']=2;
            $arr['c_state']=3;
        }
        //合同数据
        $arr['c_number'] = isset($data['c_number']) ? trim($data['c_number']) : "";
        $arr['c_img'] = isset($data['c_img']) ?  implode(',',$data['c_img']) : "";
        $arr['c_a_time'] = isset($data['c_a_time']) ? strtotime(trim($data['c_a_time'])) : "";
        $arr['c_d_time'] = isset($data['c_d_time']) ? strtotime(trim($data['c_d_time'])): "";
        $arr['c_room'] = isset($data['c_room']) ? trim($data['c_room']) : "";
        $arr['c_signing_time'] = isset($data['c_signing_time']) ? strtotime(trim($data['c_signing_time'])) : "";
        $arr['c_rent'] =  isset($data['c_rent']) ? trim($data['c_rent']) : "";
        $arr['c_rent_cont'] =  isset($data['c_rent_cont']) ? trim($data['c_rent_cont']) : "";
        $arr['c_deposit'] =  isset($data['c_deposit']) ? trim($data['c_deposit']) : "";
        $arr['c_deposit_cont'] =  isset($data['c_deposit_cont']) ? trim($data['c_deposit_cont']) : "";
        $arr['c_payment_method'] =  isset($data['c_payment_method']) ? trim($data['c_payment_method']) : "";
        $arr['c_method'] =  isset($data['c_method']) ? json_encode($data['c_method']) : "";
        $arr['c_time'] = time();
        $arr['create_id'] = create_id($data['token']);

        $t =  isset($data['contracted_housing']) ? $data['contracted_housing'] : "";

        $tenant['t_id'] =  isset($data['contract']) ? trim($data['contract']) : "";
        $tenant['t_type'] =  1;
        $tenant['t_time'] =  time();
        $tenants =  isset($data['tenant_contract']) ? $data['tenant_contract'] : "";

        $pay['pay_time'] =  isset($data['pay_time']) ? strtotime(trim($data['pay_time'])) : "";
        $pay['pay_type'] =  isset($data['pay_type']) ? trim($data['pay_type']) : "";
        $pay['pay_img'] =  isset($data['pay_img']) ? implode(',',$data['pay_img']) : "";
        $pay['a_time'] =  time();

        $datail = Db::name('tenant_management')->where('tenant_id', $tenant['t_id'])->find();
        $meter = [];
        if($t!=null){
            foreach($t as $k=>$v){
                $meter[$k]['admin_id']=$arr['create_id'];
                $meter[$k]['house_id']=$v['h_id'];//商铺或者住房id
                $meter[$k]['type']=$arr['c_room'];//判断是住房还是商铺1:住房2:商铺
                $meter[$k]['tung_num']=explode('-', $v['c_number'])[0];//栋
                $meter[$k]['unit_num']=explode('-', $v['c_number'])[1];//单元
                $meter[$k]['layer_num']=explode('-', $v['c_number'])[2];//层（暂时获取不到）
                $meter[$k]['room_number']=explode('-', $v['c_number'])[2];//房号
                $meter[$k]['create_time']=time();
                $meter[$k]['status']=1;
                $meter[$k]['num'] = 0.00;
                $meter[$k]['time'] = 0;
                $meter[$k]['tenant_id'] = $tenant['t_id'];
                $meter[$k]['tenant_name'] = $datail['tenant_name'];
                $meter[$k]['tenant_tel'] = $datail['tenant_tel'];
                if ($meter[$k]['type'] == 1) {
                    $tmp = Db::name('housing_information')->where('housing_id', $meter[$k]['house_id'])->find();
                    $meter[$k]['layer_num'] = $tmp['h_layer_num'];
                } else {
                    $tmp = Db::name('shops')->where('shops_id', $meter[$k]['house_id'])->find();
                    $meter[$k]['layer_num'] = $tmp['s_layer_num'];
                }
            }
        }

        Db::startTrans();
        try {
            $id=Db::name('contract_management')->insertGetId($arr);//添加合同
            $tenant['t_c_mid'] =  $id;
            $pay['c_id'] =  $id;
            Db::name('payment')->insert($pay);//添加合同缴费记录
            Db::name('tenant_contract')->insert($tenant);//添加合同租客
            $this->housing($t,$id, $arr['c_room']);//添加合同房源
            if($tenants!=null){
                $data=  $this->tenant($tenants,$id);//添加合同合租者
            }

            /**
             * 增加抄表记录
             */
            foreach ($meter as $m) {
                Db::name('electricity_meter')->insert($m);
                Db::name('water_meter')->insert($m);
                Db::name('gas_meter')->insert($m);
            }

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
    }

    /**
     * 添加合同和房源关联
     * @param $data 数组数据
     * @param $id 合同id
     * @param $type 商铺还是住房状态码
     * @return bool|int|string
     */

    public function housing($data,$id,$type){
        if($data!=null){
            foreach($data as $k=>$v){
                $arr['h_id']=$v['h_id'];//商铺或者住房id
                $arr['c_c_mid']=$id;//合同id
                $arr['h_type']=$type;//判断是住房还是商铺1:住房2:商铺
                $arr['number']=$v['number'];//f房号
                $arr['c_number']=$v['c_number'];//f房号
                $arr['c_area']=$v['c_area'];//面积
                $arr['c_apartment']=$v['c_apartment'];//户型
                $arr['c_rent']=$v['c_rent'];//租金
                $arr['c_deposit']=$v['c_deposit'];//押金
                $data=Db::name('contracted_housing')->insert($arr);
                if($type==1){
                    $data=Db::name('housing_information')->where(['housing_id'=>$v['h_id']])->update(['lease'=>2,'status'=>1]);
                }else{
                    $data=Db::name('shops')->where(['shops_id'=>$v['h_id']])->update(['lease'=>2,'status'=>1]);
                }

            }
            return $data;
           // return false;
        }else{
            return true;
        }
    }
    /**
     * 添加合同和租客关联
     * @param $data 数组数据
     * @param $id 合同id
     * @return bool|int|string
     */

    public function tenant($data,$id){
        if($data!=null){
            foreach($data as $k=>$v){
                $arr['t_c_mid']=$id;//合同id
                $arr['t_id']=$v;//租客id
                $arr['t_type']=2;//2代表合租
                $arr['t_time'] =  time();
                $data=Db::name('tenant_contract')->insert($arr);
            }
            return $data;
        }else{
            return true;
        }
    }

    /**
     * 合同修改回显
     * @param $id 合同id
     * @return bool|int|string
     */

    public function TmanagementOne($id){
        $data=Db::name('contract_management')->where(['c_id'=>$id])->find();//合同显示
        $data['c_img']=explode(',',$data['c_img']);
        $data['c_method']=json_encode($data['c_method']);
        $pay=Db::name('payment')->where(['c_id'=>$id])->find();//合同缴费记录
        $pay['pay_img']=explode(',',$pay['pay_img']);
        $data['payment']=$pay;
        $tenant= Db::name('tenant_contract')->alias('a')
            ->join('tenant_management b','a.t_id=b.tenant_id')
            ->where(['t_c_mid'=>$id])
            ->field('a.t_c_id,b.tenant_name,b.tenant_tel,b.tenant_idcard')
            ->where(['t_type'=>2])
            ->select();//合同合租者
        $data['tenant']=$tenant;
        $contr= Db::name('tenant_contract')->alias('a')
            ->join('tenant_management b','a.t_id=b.tenant_id')
            ->field('a.t_c_id,b.tenant_id,b.tenant_name,b.tenant_tel,b.tenant_idcard')
            ->where(['t_c_mid'=>$id])
            ->where(['t_type'=>1])
            ->find();//合同租客

        $data['contract']=$contr;
        $housing=Db::name('contracted_housing')->where(['c_c_mid'=>$id])->select();//合同房源
        $data['housing']=$housing;
        return $data;
    }
    public function management($id){
        $tenant=Db::name('tenant_contract')->where(['t_c_mid'=>$id])->where(['t_type'=>2])->select();//合同合租者

    }
    /**
     * 合同修改
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function TmanagementUpload($data){

        //合同数据
        $where['c_id']=$data['c_id'];
        $time=time();
        $e_time=strtotime(trim($data['c_d_time']))-10*24*60*60;
        if(strtotime(trim($data['c_d_time']))<$time){//逾期
            $arr['c_type']=3;
            $arr['c_state']=5;
        }elseif($e_time<$time){
            $arr['c_type']=2;
            $arr['c_state']=3;
        }
        $arr['c_number'] = isset($data['c_number']) ? trim($data['c_number']) : "";
        $arr['c_img'] = isset($data['c_img']) ?  implode(',',$data['c_img']) : "";
        $arr['c_a_time'] = isset($data['c_a_time']) ? strtotime(trim($data['c_a_time'])) : "";
        $arr['c_d_time'] = isset($data['c_d_time']) ? strtotime(trim($data['c_d_time'])): "";
        $arr['c_room'] = isset($data['c_room']) ? trim($data['c_room']) : "";
        $arr['c_signing_time'] = isset($data['c_signing_time']) ? strtotime(trim($data['c_signing_time'])) : "";
        $arr['c_rent'] =  isset($data['c_rent']) ? trim($data['c_rent']) : "";
        $arr['c_rent_cont'] =  isset($data['c_rent_cont']) ? trim($data['c_rent_cont']) : "";
        $arr['c_deposit'] =  isset($data['c_deposit']) ? trim($data['c_deposit']) : "";
        $arr['c_deposit_cont'] =  isset($data['c_deposit_cont']) ? trim($data['c_deposit_cont']) : "";
        $arr['c_payment_method'] =  isset($data['c_payment_method']) ? trim($data['c_payment_method']) : "";
        $arr['c_method'] =  isset($data['c_method']) ? json_encode($data['c_method']) : "";
        //房源
        $t =  isset($data['contracted_housing']) ? $data['contracted_housing'] : "";
        //租客
        $tenant['t_id'] =  isset($data['contract']) ? trim($data['contract']) : "";
        //缴费信息
        $pay['pay_time'] =  isset($data['pay_time']) ? strtotime(trim($data['pay_time'])) : "";
        $pay['pay_type'] =  isset($data['pay_type']) ? trim($data['pay_type']) : "";
        $pay['pay_img'] =  isset($data['pay_img']) ? implode(',',$data['pay_img']) : "";
       /* Db::name('contract_management')->where($where)->update($arr);//添加合同
        Db::name('payment')->where(['pay_id'=>$data['pay_id']])->update($pay);//添加合同缴费记录
        if ($tenant['t_id']!=null){
            Db::name('tenant_contract')->where(['t_c_mid'=>$data['c_id']])->where(['t_type'=>1])->update($tenant);//添加合同租客
        }
        $this->c_housing($t, $arr['c_room']);//添加合同房源*/

        Db::startTrans();
        try {
            Db::name('contract_management')->where($where)->update($arr);//添加合同
            Db::name('payment')->where(['pay_id'=>$data['pay_id']])->update($pay);//添加合同缴费记录
            if ($tenant['t_id']!=null){
                Db::name('tenant_contract')->where(['t_c_mid'=>$data['c_id']])->where(['t_type'=>1])->update($tenant);//添加合同租客
            }
            $this->c_housing($t, $arr['c_room']);//添加合同房源
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
    }


    /**
     * 编辑合同和房源关联
     * @param $data 数组数据
     * @param $id 合同id
     * @param $type 商铺还是住房状态码
     * @return bool|int|string
     */

    public function c_housing($data,$type){
        if($data!=null){
            foreach($data as $k=>$v){
                $arr['h_id']=$v['h_id'];//商铺或者住房id
                $arr['h_type']=$type;//判断是住房还是商铺1:住房2:商铺
                $arr['number']=$v['number'];//f房号
                $arr['c_number']=$v['c_number'];//f房号
                $arr['c_area']=$v['c_area'];//面积
                $arr['c_apartment']=$v['c_apartment'];//户型
                $arr['c_rent']=$v['c_rent'];//租金
                $arr['c_deposit']=$v['c_deposit'];//押金
                Db::name('contracted_housing')->where(['c_h_id'=>$v['c_h_id']])->update($arr);
            }
            return true;
            // return false;
        }else{
            return true;
        }
    }

    /**
     * 编辑的时候删除合租人
     * @param $id 合同id
     * @return bool|int|string
     */
    public function tenantDel($id){
        $data=Db::name('tenant_contract')->where(['t_c_id'=>$id])->delete();
        return $data;
    }
    /**
     * 编辑的时候添加合租人
     * @param $data 数组数据
     * @return bool|int|string
     */

    public function tenantAdd($data){
        $arr['t_c_mid']=trim($data['t_c_mid']);//合同id
        $phone=Db::name('tenant_management')->where(['tenant_tel'=>$data['phone']])->find();
        if($phone==null){
            return 3;
        }
        $arr['t_id']=$phone['tenant_id'];//租客id
        $count=Db::name('tenant_contract')->where($arr)->find();
        if($count!=null){
            return 2;
        }
        $arr['t_type']=2;//2代表合租
        $arr['t_time'] =  time();
        $data=Db::name('tenant_contract')->insert($arr);
        return $data;
    }
    /**
     * 编辑的时候删除房源
     * @param $id 合同id
     * @return bool|int|string
     */
    public function housingDel($id){
        $data=Db::name('contracted_housing')->where(['c_h_id'=>$id])->find();
        if($data['h_type']==1){
            $data=Db::name('housing_information')->where(['housing_id'=>$data['h_id']])->update(['lease'=>1]);
        }else{
            $data=Db::name('shops')->where(['shops_id'=>$data['h_id']])->update(['lease'=>1]);
        }
        $data=Db::name('contracted_housing')->where(['c_h_id'=>$id])->delete();
        return $data;
    }
    /**
     * 编辑的时候删除合租人
     * @param $data 数组数据
     * @return bool|int|string
     */

    public function housingAdd($data){
        $date=$this->h_housing($data);
      //  var_dump($date);exit;
        $arr['h_id']=$date['h_id'];//商铺或者住房id
        $arr['c_c_mid']=$data['c_id'];//合同id
        $arr['h_type']=$data['type'];//判断是住房还是商铺1:住房2:商铺
        $arr['c_number']=$date['unit'];//f房号
        $arr['number']=$date['number'];//f房号
        $arr['c_area']=$date['area'];//面积
        $arr['c_apartment']=$date['apartment'];//户型
        $arr['c_rent']=$date['money'];//租金
        if($data['type']==1){
            if($date==null){
                return 2;
            }
            $id=Db::name('contracted_housing')->insertGetId($arr);
            $data=Db::name('housing_information')->where(['housing_id'=>$date['h_id']])->update(['lease'=>2]);
        }else{
            if($date==null){
                return 2;
            }
            $id=Db::name('contracted_housing')->insertGetId($arr);
            $data=Db::name('shops')->where(['shops_id'=>$date['h_id']])->update(['lease'=>2]);
        }
        $data=Db::name('contracted_housing')->where(['c_h_id'=>$id])->find();
        return $data;
    }

    /**
     * 类型房源选择
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function h_housing($data){
        //处理数据1是住房  2是商铺
        if($data['type']==1){
            $where['h_state']=1;
            $where['lease']=1;
            $where['create_id'] = create_id($data['token']);
            if($data['tung_num']!=null){
                $where['h_tung_num']=$data['tung_num'];//栋
                $where['h_unit_num']=$data['unit_num'];//单元
                $where['h_room_number']=$data['room_number'];//房号
            }
            $data=Db::name('housing_information')
                ->field('housing_id,h_tung_num,h_unit_num,h_room_number,h_money,h_area,h_root,h_guest_room,h_toilet')
                ->where($where)
                ->find();
            if($data!=null){
                $data['unit']=$data['h_tung_num'].'-'.$data['h_unit_num'].'-'.$data['h_room_number'];
                $data['apartment']=$data['h_root'].'室'.$data['h_guest_room'].'厅'.$data['h_toilet'].'卫';
                $data['money']=$data['h_money'];
                $data['h_id']=$data['housing_id'];
                $data['area']=$data['h_area'];
                $data['number']=$data['h_room_number'];
            }
            return $data;
        }else{
            $where['s_state']=1;
            $where['lease']=1;
            $where['create_id'] = create_id($data['token']);
            if($data['tung_num']!=null){
                $where['s_tung_num']=$data['tung_num'];//栋
                $where['s_unit_num']=$data['unit_num'];//单元
                $where['s_room_number']=$data['room_number'];//单元
            }
            $data=Db::name('shops')
                ->field('shops_id,s_tung_num,s_unit_num,s_room_number,s_money,s_area,s_face_width,s_layer_depth,s_depth')
                ->where($where)
                ->find();
            if($data!=null){
                $data['unit']=$data['s_tung_num'].'-'.$data['s_unit_num'].'-'.$data['s_room_number'];
                $data['apartment']='面宽:'.$data['s_face_width'].'层深:'.$data['s_layer_depth'].'进深:'.$data['s_depth'];
                $data['money']=$data['s_money'];
                $data['h_id']=$data['shops_id'];
                $data['area']=$data['s_area'];
                $data['number']=$data['s_room_number'];
            }
            return $data;
        }
    }

    /**
     * 合同显示
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function index(){
        $data = input();
        $page=isset($data['page']) ? trim($data['page']) : 1;
        $number=isset($data['number']) ? trim($data['number']) : '';
        $e_time=isset($data['e_time']) ? strtotime(trim($data['e_time'])) : '';
        $pay_state=isset($data['pay_state']) ? trim($data['pay_state']) : '';
        $a_time=isset($data['a_time']) ? strtotime(trim($data['a_time'])) : '';
        $types=isset($data['types']) ? trim($data['types']) : '';
        $c_state=isset($data['c_state']) ? trim($data['c_state']) : '';
        $where=[];
        $create_id=create_id($data['token']);
        $where['a.create_id'] = create_id($data['token']);
        if($number!=null){
            $where['e.c_number|c.tenant_name'] = ['like',"%".$number."%"];
        }
        if($e_time!=null){
            $where['a.c_d_time'] = array('elt',$e_time);
        }
        if($a_time!=null){
            $where['a.c_a_time'] = array('egt',$a_time);
        }
        if($pay_state!=null){
            $where['a.c_pay'] = array('eq',$pay_state);
        }
        if($c_state!=null){
            $where['a.c_state'] = array('eq',$c_state);
        }
        if($types!=null){
            $where['a.c_type'] = array('eq',$types);
        }
        $count=Db::name('contract_management')
            ->alias('a')
            ->join('tenant_contract b','a.c_id=b.t_c_mid')
            ->join('tenant_management c','b.t_id=c.tenant_id')
            ->join('admin_user d','c.tenant_agent=d.admin_id')
            ->join('contracted_housing e','a.c_id=e.c_c_mid')
            ->join('payment f','a.c_id=f.c_id')
            ->group('a.c_id')
            ->where(['b.t_type'=>1])
            ->where($where)
            ->count();
        $data=Db::name('contract_management')
            ->alias('a')
            ->join('tenant_contract b','a.c_id=b.t_c_mid')
            ->join('tenant_management c','b.t_id=c.tenant_id')
            ->join('admin_user d','c.tenant_agent=d.admin_id')
            ->join('contracted_housing e','a.c_id=e.c_c_mid')
            ->join('payment f','a.c_id=f.c_id')
            ->group('a.c_id')
            ->Distinct(true)
            ->field('a.c_id,a.c_room,a.c_number,a.c_a_time,a.c_d_time,a.c_time,a.c_rent,a.c_pay,a.c_type,a.c_state,c.tenant_name,c.tenant_tel,d.name,a.c_signing_time,f.pay_state')
            ->where(['b.t_type'=>1])
            ->where($where)
            ->page($page, 10)
           // ->order("a.c_id desc")
            ->order("a.c_id desc,f.a_time asc")
            ->select();

        foreach($data as $k=>$v){
            $data[$k]['housing']=Db::name('contracted_housing')
                ->field('c_number')
                ->where(['c_c_mid'=>$v['c_id']])
               // ->where($where)
                ->select();
            $type=Db::name('payment')
                ->field('pay_state')
                ->where(['c_id'=>$v['c_id']])
                ->order('pay_id asc')
                // ->where($where)
                ->find();
            $data[$k]['type']=$type['pay_state'];
        }
      //  var_dump($data);exit;
        $wil_expire=Db::name('contract_management')
            ->where(['c_type'=>2])
             ->where(['create_id'=>$create_id])
            ->count();//将到期
        //var_dump($create_id);exit;
        $overdue=Db::name('contract_management')
            ->where(['c_type'=>3])
            ->where(['create_id'=>$create_id])
            ->count();//已逾期
        $i['h_state']=1;
        $h_count=Db::name('housing_information')
            ->where(['create_id'=>$create_id])
            ->where($i)
            ->count();
        $s_count=Db::name('shops')
            ->where(['create_id'=>$create_id])
            ->where(['s_state'=>1])
            ->count();
        $s_null=Db::name('shops')
            ->where(['create_id'=>$create_id])
            ->where(['s_state'=>1])
            ->where(['lease'=>1])
            ->count();
        $h_null=Db::name('housing_information')
            ->where(['create_id'=>$create_id])
            ->where(['h_state'=>1])
            ->where(['lease'=>1])
            ->count();
     //   var_dump($count,$data);exit;
        $date['data']=$data;
        $date['count']=$count;
        $date['wil_expire']=$wil_expire;//将到期
        $date['overdue']=$overdue;//已预期数量
        $date['h_null']=$h_null;//住房空置数量
        $date['h_number']=$h_count;//住房数量
        $date['s_null']=$s_null;//商铺空置数量
        $date['s_number']=$s_count;//商铺数量
        $date['housing_count']=$h_count+$s_count;//总数
        return $date;
    }


    /**
     * 合同回显
     * @param $id 合同id
     * @return bool|int|string
     */

    public function T_One($id){
        $data=Db::name('contract_management')->where(['c_id'=>$id])->find();//合同显示
        $data['c_img']=explode(',',$data['c_img']);
        $data['c_method']=json_decode($data['c_method']);
        $pay=Db::name('payment')->where(['c_id'=>$id])->select();//合同缴费记录
        foreach($pay as $k=>$v){
            $pay[$k]['pay_img']=explode(',',$v['pay_img']);
        }

        $data['payment']=$pay;
        $tenant= Db::name('tenant_contract')->alias('a')
            ->join('tenant_management b','a.t_id=b.tenant_id')
            ->where(['t_c_mid'=>$id])
            ->field('a.t_c_id,b.tenant_name,b.tenant_tel,b.tenant_idcard')
            ->where(['t_type'=>2])
            ->select();//合同合租者


        $data['tenant']=$tenant;
        $resident = Db::name('resident_users')->alias('r')
            ->join('contracted_housing c','r.resident_agent=c.c_h_id')
            ->field('*')
            ->where(['c.c_c_mid'=>$id])
            ->where(['r.resident_state'=>1])
            ->select();//合同入住者

        $data['resident']=$resident;
        $contr= Db::name('tenant_contract')->alias('a')
            ->join('tenant_management b','a.t_id=b.tenant_id')
            ->field('a.t_c_id,b.tenant_name,b.tenant_id,b.tenant_tel,b.tenant_idcard')
            ->where(['t_c_mid'=>$id])
            ->where(['t_type'=>1])
            ->find();//合同租客

        $data['contract']=$contr;
        $housing=Db::name('contracted_housing')->where(['c_c_mid'=>$id])->select();//合同房源
        $data['housing']=$housing;
      //  var_dump($data);exit;
        return $data;
    }
    /**
     * 合同缴费删除
     * @param $id 合同id
     * @return bool|int|string
     */

    public function payDel($id){
        $pay=Db::name('payment')->where(['pay_id'=>$id])->delete();//合同缴费记录
        return $pay;
    }
    /**
     * 合同缴费添加
     * @param $data 缴费记录
     * @return bool|int|string
     */
    public function payAdd($data){
        $pay['pay_time'] =  isset($data['pay_time']) ? strtotime(trim($data['pay_time'])) : "";
        $pay['pay_type'] =  isset($data['pay_type']) ? trim($data['pay_type']) : "";
        $pay['c_id'] =  isset($data['c_id']) ? trim($data['c_id']) : "";
        $pay['pay_img'] =  isset($data['pay_img']) ? implode(',',$data['pay_img']) : "";
        if($pay['c_id']!=null){
            $date=Db::name('contract_management')->where(['c_id'=>$pay['c_id']])->update(['c_pay'=>2]);//合同缴费记录
            $pay=Db::name('payment')->insert($pay);//合同缴费记录
        }
//        $data=Db::name('payment')->where(['pay_id'=>$pay])->find();//合同缴费记录
//        $data['pay_img']=explode(',',$data['pay_img']);//合同缴费记录
        return $pay;
    }

    /**
     * 根据租客id找到合同id
     * @param $tenant_id
     * @return array|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function tenantContractId($tenant_id, $page) {
        $list = Db::name('tenant_contract')
            ->field('t_c_mid')
            ->where('t_type', 1)
            ->page($page, 10)
            ->order('t_c_mid desc')
            ->where('t_id', $tenant_id)
            ->select();
        $count = Db::name('tenant_contract')
            ->where('t_id', $tenant_id)
            ->where('t_type', 1)
            ->count();
        $data['data'] = $list;
        $data['total'] = $count;
        return $data;
    }

    /**
     * 根据租客id找到合同id
     * @param $tenant_id
     * @return array|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function tenantContractId2($tenant_id) {
        $list = Db::name('tenant_contract')
            ->field('t_c_mid')
            ->where('t_type', 1)
            ->order('t_c_mid desc')
            ->where('t_id', $tenant_id)
            ->select();
        $data = $list;
        return $data;
    }

    /**
     * 根据合同id找到所有租客
     * @param $contract_id
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function contractIdAllTenant($contract_id) {
        $data = Db::name('tenant_contract')
            ->field('t_c_id, t_c_mid, t_id, t_type')
            ->where('t_type', 1)
            ->where('t_c_mid', $contract_id)
            ->order('t_time desc')
            ->find();
        return $data;
    }


    /**
     * 根据合同id查询住房
     * @param $id 合同id
     * @return bool|int|string
     */

    public function check_In($id){
        //根据合同查找合同住房
        $date=Db::name('contracted_housing')
            ->field('c_number')
            ->where(['c_c_mid'=>$id])
            ->select();
        $date['count']=Db::name('contracted_housing')
            ->field('c_number')
            ->where(['c_c_mid'=>$id])
            ->count();
        return $date;
    }

    /**
     * 添加入住者
     * @param $data 入住者数据
     * @return bool|int|string
     */

    public function contracte_housing($data){
        //添加操作用户id
        /*$uid=get_user_id($data['token']);
        $arr['te_uid'] = $uid;*/

        $user= Db::name('resident_users')->where(['resident_agent'=>$data['resident_agent']])->where(['resident_idcard'=>$data['resident_idcard']])->find();
        if($user!=null){
            return false;
        }
        if(strpos($data['resident_front'],'uploads/') == false){
            $img1=base64_image_content("data:image/jpg;base64,".$data['resident_front']);
            $arr['resident_front'] = $img1;
        }else{
            $arr['resident_front'] = $data['resident_front'];
        }
        if(strpos($data['resident_back'],'uploads/') == false){
            $img2=base64_image_content("data:image/jpg;base64,".$data['resident_back']);
            $arr['resident_back'] =$img2 ;
        }else{
            $arr['resident_back'] = $data['resident_back'];
        }
        //处理数据
        $arr['resident_idcard'] = isset($data['resident_idcard']) ? trim($data['resident_idcard']) : "";
        $arr['resident_agent'] = isset($data['resident_agent']) ? trim($data['resident_agent']) : "";
        $arr['resident_name'] = isset($data['resident_name']) ? trim($data['resident_name']) : "";
        $arr['resident_sex'] = tenant_sex(isset($data['resident_sex']) ? trim($data['resident_sex']) : "");
        $arr['resident_tel'] = isset($data['resident_tel']) ? trim($data['resident_tel']) : "";
       /* $arr['resident_front'] = isset($data['resident_front']) ?  base64_image_content("data:image/jpg;base64,".$data['resident_front']) : "";
        $arr['resident_back'] = isset($data['resident_back']) ?  base64_image_content("data:image/jpg;base64,".$data['resident_back']) : "";*/
        $arr['resident_famous_race'] = isset($data['resident_famous_race']) ? trim($data['resident_famous_race']) : "";
        $arr['r_date_of_birth'] = isset($data['r_date_of_birth']) ? $data['r_date_of_birth']: "";
        $arr['resident_issue'] = isset($data['resident_issue']) ? $data['resident_issue']  : "";
        $arr['resident_address'] = isset($data['resident_address']) ? $data['resident_address']  : "";
        $arr['resident_valid_date'] = isset($data['resident_valid_date']) ? $data['resident_valid_date']  : "";
        $arr['resident_relationship'] = isset($data['resident_relationship']) ? $data['resident_relationship']  : "";
        $arr['resident_a_time'] = time();
        $data=Db::name('resident_users')->insertGetId($arr);
        if($data){
            $data= Db::name('resident_users')->where(['resident_id'=>$data])->find();
            return $data;
        }else{
            return false;
        }
    }
    /**
     * 查找合同关联房源
     * @param $id 合同is
     * @param $c_room 房源(1:住房2:商铺)
     * @return bool|int|string
     */

    public function s_housing($id,$c_room=''){
        //处理数据
        $count=Db::name('contracted_housing')->where(['c_c_mid'=>$id])->count();//住房数量
        //判断合同关联房源数量
        if($count>1){
            if($c_room==1){
                $list=Db::name('contracted_housing')
                    ->alias('a')
                    ->join('housing_information b','a.h_id=b.housing_id')
                    ->field('a.*,b.h_root,b.h_guest_room,b.h_toilet')
                    ->where(['c_c_mid'=>$id])
                    ->select();
                foreach ($list as $k=>$v){
                    $list[$k]['apartment']=$v['h_root'].'室'.$v['h_guest_room'].'厅'.$v['h_toilet'].'卫';
                }
            }else{
                $list=Db::name('contracted_housing')
                    ->alias('a')
                    ->join('shops b','a.h_id=b.shops_id')
                    ->field('a.*,b.s_face_width,b.s_layer_depth,b.s_depth')
                    ->where(['c_c_mid'=>$id])
                    ->select();
                foreach ($list as $k=>$v){
                    $list[$k]['apartment']='面宽:'.$v['s_face_width'].'层深:'.$v['s_layer_depth'].'进深:'.$v['s_depth'];
                }
            }
            $data['data']=$list;
            $data['count']= $count;
            $data['c_id']= $id;
            $data['c_room']= $c_room;
        }else{
            $input = input();
            $data=Db::name('contracted_housing')->where(['c_c_mid'=>$id])->find();
            //判断房源是住房还是商铺  住房显示入住者信息商铺显示商铺行业类型
            if($c_room==1){
                $data['users']=Db::name('resident_users')
                    ->field('resident_id,resident_name,resident_tel,resident_idcard,resident_relationship')
                    ->where(['resident_agent'=>$data['c_h_id']])
                    ->select();
            }else{
                $data['industry']=Db::name('settings')
                    ->where(['create_id'=> create_id($input['token'])] )
                    ->field('shop_industry')
                    ->find();
            }
            //物品
            $data['content']= $data['count'];
            $data['count']= $count;

            $data['c_id']= $id;
            $data['c_room']= $c_room;
            $data['items']= Db::name('handover_items')->where(['c_h_id'=>$data['c_h_id']])->select();
        }
        return $data;

    }
    /**
     * 添加物品
     * @param $data 物品数据
     * @return bool|int|string
     */
    public function itemsAdd($data){
        //处理数据
        $arr['h_i_name'] = isset($data['h_i_name']) ? trim($data['h_i_name']) : "";
        $arr['number'] = isset($data['number']) ? trim($data['number']) : "";
        $arr['c_h_id'] = isset($data['c_h_id']) ? trim($data['c_h_id']) : "";
        $arr['a_time'] = time();
        $id=Db::name('handover_items')->insertGetId($arr);//住房信息
        if($id){
            $data= Db::name('handover_items')->where(['h_i_id'=>$id])->find();
            return $data;
        }else{
            return false;
        }
    }
    /**
     * 删除物品
     * @param $id 物品id
     * @return bool|int|string
     */
    public function itemsDel($id){
        //处理数据
        $data=Db::name('handover_items')->where(['h_i_id'=>$id])->delete();//住房信息
        if($data){
            return true;
        }else{
            return false;
        }
    }
    /**
     * 删除入住者
     * @param $id 入住者表id
     * @return bool|int|string
     */
    public function contracted_del($id){
        //处理数据
        $data=Db::name('resident_users')->where(['resident_id'=>$id])->delete();//住房信息
        if($data){
            return true;
        }else{
            return false;
        }
    }
    /**
     * 多个住房商铺或者房源点击入住显示入住信息
     * @param $c_id 合同id
     * @param $id 合同和房源关联id
     * @param $c_room 房源(1:住房2:商铺)
     * @return bool|int|string
     */

    public function CheckIn($id,$c_room,$c_id){
        //处理数据
        $data=Db::name('contracted_housing')->where(['c_h_id'=>$id])->find();
        //判断房源是住房还是商铺  住房显示入住者信息商铺显示商铺行业类型
        if($c_room==1){
            $data['users']=Db::name('resident_users')
                ->field('resident_id,resident_name,resident_tel,resident_idcard,resident_relationship')
                ->where(['resident_agent'=>$data['c_h_id']])
                ->select();
        }else{
            $data['industry']=Db::name('settings')
                ->field('shop_industry')
                ->find();
        }
        //物品
        $data['c_room']= $c_room;
        $data['c_id']= $c_id;
        $data['items']= Db::name('handover_items')->where(['c_h_id'=>$data['c_h_id']])->select();
        return $data;
    }

    /**
     * 根据房号和状态找到合同房源中间表信息
     * @param $type 商铺还是住房
     * @param $number 房号
     * @return int|string
     */
    public function housingInformation($type,$number){
        //处理数据
        $arr['h_type']=$type;
        $arr['number']=$number;
        $data=Db::name('contracted_housing')->where($arr)->order('c_h_id desc')->find();
        return $data;
    }
    /**
     * 根据房号和状态找到合同房源中间表信息
     * @param $id 合同id
     * @return int|string
     */
    public function userList($id){
        //处理数据
        $arr['t_c_mid']=$id;
        $arr['t_type']=2;
        $data=Db::name('tenant_contract')->alias('a')
            ->field('b.tenant_name,b.tenant_tel,b.tenant_idcard,a.t_c_id')
            ->join('tenant_management b','a.t_id=b.tenant_id')
            ->where($arr)->order('t_c_id asc')
            ->select();
        return $data;
    }
    /**
     * 根据房号和状态找到合同房源中间表信息
     * @param $id 合同id
     * @return int|string
     */
    public function housingList($id){
        //处理数据
        $arr['c_c_mid']=$id;
        $data=Db::name('contracted_housing')->where($arr)->order('c_h_id desc')->select();
        return $data;
    }
    /**
     * 点击保存和办理完成
     * @param $data 数据
     * @return bool|int|string
     */

    public function housingPreservationAdd($data){
        //处理数据
        $arr['count']=isset($data['count']) ? trim($data['count']) : "";
        $arr['c_industry']=isset($data['industry']) ? trim($data['industry']) : "";
        $datas=Db::name('contracted_housing')->where(['c_h_id'=>$data['c_h_id']])->update($arr);
        //判断是点击保存还是办理完成
        if($data['type']==2){
            $i=Db::name('contracted_housing')->where(['c_h_id'=>$data['c_h_id']])->find();
            //找到对应的房源是住房还是商铺
            if($i['h_type']==1){
                //房源状态已入住
                Db::name('housing_information')->where(['housing_id'=>$i['h_id']])->update(['status'=>2]);
            }else{
                //商铺状态  已开业
                Db::name('shops')->where(['shops_id'=>$i['h_id']])->update(['status'=>2]);
            }
            $data=Db::name('contract_management')->where(['c_id'=>$data['c_id']])->update(['c_state'=>2]);
        }
        return $data;
    }
    /**
     * 点击保存和办理完成
     * @param $data 数据
     * @return bool|int|string
     */

    public function contractCompletion($data){
        //处理数据
        if($data['type']==2){
            $data=Db::name('contract_management')->where(['c_id'=>$data['c_id']])->find();
            $i=Db::name('contracted_housing')->where(['c_c_mid'=>$data['c_id']])->select();
            //找到对应的房源是住房还是商铺
            if($data['c_room']==1){
                //房源状态已入住
                foreach ($i as $k=>$v){
                    Db::name('housing_information')->where(['housing_id'=>$v['h_id']])->update(['status'=>2]);
                }
            }else{
                //商铺状态  已开业
                foreach ($i as $k=>$v){
                    Db::name('shops')->where(['shops_id'=>$v['h_id']])->update(['status'=>2]);
                }
            }
            $data=Db::name('contract_management')->where(['c_id'=>$data['c_id']])->update(['c_state'=>2]);
        }
        return true;
    }
    /**
 * 查看租赁信息
 * @param $id 合同is
 * @return bool|int|string
 */

    public function Lease_information($id){
        //处理数据
        $count=Db::name('contracted_housing')->where(['c_c_mid'=>$id])->count();//住房数量
        $data=$this->T_One($id);
        //判断合同房源数量
        if($count>1) {
            $i = Db::name('contracted_housing')
                ->field('c_h_id,c_number,c_industry')
                ->where(['c_c_mid'=>$id])
                ->select();
            //判断住房还是商铺
            if ($data['c_room'] == 1) {
                //查找合同关联房源信息
                foreach ($i as $k=>$v){
                    $i[$k]['user_name']= Db::name('resident_users')
                        ->field('resident_name')
                        ->where(['resident_agent'=>$v['c_h_id']])
                        ->select();
                }
            }
            $data['housing_information']=$i;
            return $data;
        }else{
            $i = Db::name('contracted_housing')
                ->field('c_h_id,c_number,c_industry')
                ->where(['c_c_mid'=>$id])
                ->find();
            //var_dump($i['c_h_id']);exit;
            //交接物品
            $i['items']= Db::name('handover_items')->where(['c_h_id'=>$i['c_h_id']])->select();
          //  var_dump($i);exit;
            //判断住房还是商铺
            if ($data['c_room'] == 1) {
                //入住人
                $i['users']=Db::name('resident_users')
                    ->field('resident_name,resident_tel,resident_idcard,resident_relationship')
                    ->where(['resident_agent'=>$i['c_h_id']])
                    ->select();
            }
            $data['housing_information']=$i;
            //var_dump($data);exit;
            return $data;
        }
    }

    /**
     * 查看租赁信息
     * @param $c_room 住房还是商铺
     * @param $id  房源关联表id
     * @return bool|int|string
     */

    public function housingItems($id,$c_room){
        //处理数据
        $i = Db::name('contracted_housing')
            ->field('c_h_id,c_number,c_industry,count')
            ->where(['c_h_id'=>$id])
            ->find();
        //交接物品
        $i['items']= Db::name('handover_items')->where(['h_i_id'=>$i['c_h_id']])->select();
        //判断住房还是商铺
        if ($c_room == 1) {
            //入住人
            $i['user']=Db::name('resident_users')
                ->field('resident_name,resident_tel,resident_idcard')
                ->where(['resident_agent'=>$i['c_h_id']])
                ->select();
        }
        return $i;
    }
    /**
     * 点击退租
     * @param $id 合同id
     * @return bool|int|string
     */

    public function rentWithdrawal($id){
            //处理数据
            $count=Db::name('contracted_housing')->where(['c_c_mid'=>$id])->count();//住房数量
            $arr['rent_time'] = time();
            Db::name('contract_management')->where(['c_id'=>$id])->update($arr);//合同
            $contract=Db::name('contract_management')->where(['c_id'=>$id])->find();//合同
            Db::name('contract_management')->where(['c_id'=>$id])->update(['c_state'=>4]);//合同
            //判断合同关联房源数量
            if($count>1){
                if($contract['c_room']==1){
                    $list=Db::name('contracted_housing')
                        ->alias('a')
                        ->join('housing_information b','a.h_id=b.housing_id')
                        ->field('a.*,b.h_root,b.h_guest_room,b.h_toilet')
                        ->where(['c_c_mid'=>$id])
                        ->select();
                    foreach ($list as $k=>$v){
                        $list[$k]['apartment']=$v['h_root'].'室'.$v['h_guest_room'].'厅'.$v['h_toilet'].'卫';
                    }
                }else{
                    $list=Db::name('contracted_housing')
                        ->alias('a')
                        ->join('shops b','a.h_id=b.shops_id')
                        ->field('a.*,b.s_face_width,b.s_layer_depth,b.s_depth')
                        ->where(['c_c_mid'=>$id])
                        ->select();
                    foreach ($list as $k=>$v){
                        $list[$k]['apartment']='面宽:'.$v['s_face_width'].'层深:'.$v['s_layer_depth'].'进深:'.$v['s_depth'];
                    }
                }
                $data['data']=$list;
                $data['count']= $count;
                $data['c_id']= $id;
                $data['c_room']= $contract['c_room'];
            }else{
                $data=Db::name('contracted_housing')->where(['c_c_mid'=>$id])->find();
                if($data['img']!=null){
                    $data['img']=explode(',',$data['img']);
                }else{
                    $data['img']=[];
                }

                //判断房源是住房还是商铺  住房显示入住者信息商铺显示商铺行业类型  handle
                $data['count']= $count;
                $data['c_id']= $id;
                $data['c_room']= $contract['c_room'];
                //物品
                $data['items']= Db::name('handover_items')->where(['c_h_id'=>$data['c_h_id']])->select();
            }
            //判断有没有发起结算
            $rent_withdrawal=Db::name('rent_withdrawal')->where(['c_id'=>$id])->find();
            if($rent_withdrawal==null){
                $data['settlement']=2;
            }else{
                $data['settlement']=1;
            }
            return $data;
    }
    /**
     * 点击退租
     * @param $id 合同房源id
     * @return bool|int|string
     */

    public function housingItmes($id){
        $data=Db::name('contracted_housing')->where(['c_h_id'=>$id])->find();
        //判断房源是住房还是商铺  住房显示入住者信息商铺显示商铺行业类型  handle
        $data['c_id']= $data['c_c_mid'];
        $data['c_room']= $data['h_type'];
        //物品
        $data['items']= Db::name('handover_items')->where(['c_h_id'=>$data['c_h_id']])->select();
        return $data;
    }
    /**
     * 退租数据
     * @param $data 退租数据
     * @return bool|int|string
     */

    public function itmesExamine($data){

        $arr['loss'] = isset($data['loss']) ? trim($data['loss']) : "";
        $arr['loss_disposal'] = isset($data['loss_disposal']) ? trim($data['loss_disposal']) : "";
        $arr['img'] = $arr['img'] = isset($data['img']) ?  implode(',',$data['img']) : "";

        Db::startTrans();
        try {
            $this->items($data['items']);
            Db::name('contracted_housing')->where(['c_h_id'=>$data['c_h_id']])->update($arr);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
    }

    /**
     * 理物品情况
     * @param $data 退租数据
     * @return bool|int|string
     */

    public function items($data){
        if($data!=null) {
            foreach ($data as $k => $v) {
                $arr['return'] = $v['return'];//归还情况
                $arr['handle'] = $v['handle'];//处理情况
                Db::name('handover_items')->where(['h_i_id' => $v['h_i_id']])->update($arr);
            }
            return true;
        }else{
            return true;
        }
    }
    /**
     * 取消退房
     * @param $id 合同id
     * @return bool|int|string
     */

    public function CancellationCheckOut($id){
        $data=Db::name('contract_management')->where(['c_id'=>$id])->update(['c_state'=>2]);//合同
        return $data;
    }
    /**
     * 退租显示
     * @param $id 合同id
     * @return bool|int|string
     */

    public function SubmitRentRebate($id){
        $data=$this->T_One($id);
        $data['rent_withdrawal']=Db::name('rent_withdrawal')->where(['c_id'=>$id])->find();
        return $data;
    }

    /** 退组提交
     * @param $data 退租信息
     * @return bool|int|string
     */
    public function SubmitRentRebateAdd($data){
        $arr['initiator'] = isset($data['initiator']) ? trim($data['initiator']) : "";
        $arr['rent_time'] = isset($data['rent_time']) ? trim($data['rent_time']) : "";

        $arr['payment'] = isset($data['payment']) ? trim($data['payment']) : "";
        $arr['c_id'] = isset($data['c_id']) ? trim($data['c_id']) : "";
        $arr['liquidated_damages'] = isset($data['liquidated_damages']) ? trim($data['liquidated_damages']) : "";
        $a = new ApartmentCost();
        $data = $a->generateOneBill($arr['c_id']);// 生成账单
        $data=Db::name('contract_management')->where(['c_id'=>$arr['c_id']])->update(['c_pay'=>2]);//住房信息
        $data=Db::name('rent_withdrawal')->insert($arr);//住房信息
        return $data;
    }
    /** 退租点击完成
     * @param $id 合同id
     * @return bool|int|string
     */
    public function rentRefundCompleted($id){
        //处理数据
        $list=Db::name('contracted_housing')->where(['c_c_mid'=>$id])->select();//住房
        $contract=Db::name('contract_management')->where(['c_id'=>$id])->find();//合同

        $arr['status']=3;
        $arr['lease']=1;
        Db::startTrans();
        try {
            if($contract['c_room']==1){
                foreach ($list as $k=>$v){
                    $list=Db::name('housing_information')->where(['housing_id'=>$v['h_id']])->update($arr);//状态修改
                }
            }else{
                foreach ($list as $k=>$v){
                    $list=Db::name('shops')->where(['shops_id'=>$v['h_id']])->update($arr);//状态修改
                }
            }
            $i['c_state']=6;
            $i['c_type']=4;
            $contract=Db::name('contract_management')->where(['c_id'=>$id])->update($i);//合同
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
    }
    /**
     * 查看租赁信息
     * @param $id  房源关联表id
     * @return bool|int|string
     */

    public function checkInformation($id){
        //处理数据
        $i = Db::name('contracted_housing')
            ->where(['c_h_id'=>$id])
            ->find();
        if($i['img']!=null){
            $i['img']=explode(',',$i['img']);
        }else{
            $i['img']=[];
        }

        //交接物品
        $i['items']= Db::name('handover_items')->where(['h_i_id'=>$i['c_h_id']])->select();
        return $i;
    }
    /**
     * 合同状态改变
     * @return \think\response\Json
     */
    public function contractType(){
        $wheres['c_type'] = array('lt',3);
        $i = Db::name('contract_management')->where($wheres)->select();
        $time=time();
        foreach ($i as $k=>$v){
            //将到期
            $e_time=$v['c_d_time']-10*24*60*60;
            if($v['c_d_time']<$time){//逾期
                Db::name('contract_management')->where(['c_id'=>$v['c_id']])->update(['c_type'=>3]);
                Db::name('contract_management')->where(['c_id'=>$v['c_id']])->update(['c_state'=>5]);
            }elseif($e_time<$time){
                Db::name('contract_management')->where(['c_id'=>$v['c_id']])->update(['c_type'=>2]);
                Db::name('contract_management')->where(['c_id'=>$v['c_id']])->update(['c_state'=>3]);

            }
        }
    }
    /**
     * 预约看房列表
     * @return \think\response\Json
     */
    public function orderHouse($data){
        $page=isset($data['page']) ? trim($data['page']) : 1;
        $types=isset($data['type']) ? trim($data['type']) : '';
        $a_time = isset($data['a_time']) ? strtotime(trim($data['a_time'])) : "";
        $e_time = isset($data['e_time']) ? strtotime(trim($data['e_time'])) : "";
        $phone = isset($data['phone']) ? trim($data['phone']) : "";
        $where=[];
        $where['a.admin_id']= create_id($data['token']);
        if($types!=null){
            $where['a.admin_status'] = array('eq',$types);
        }
        if($phone!=null){
            $where['b.tel|b.name'] = ['like',"%".$phone."%"];
            //$where['b.tel|b.tel'] = array('eq',$phone);
        }
        if($a_time!=null){
            $where['a.create_time'] = array('between', array($a_time,$e_time+1*24*60*60));
          //  $where['a.create_time'] = array(array('gte',$a_time),array('lte',$e_time)) ;
        }
       // var_dump($where);exit;
        $beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
        $endToday=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
      //  var_dump(date('Y-m-d H:i:s',1567492454),date('Y-m-d',$endToday));exit;
        $u_time['create_time'] =  array('between', array($beginToday,$endToday));

        $user=Db::name('order_house')->where(['admin_id'=>create_id($data['token'])])->count();//预约看房总数量
        $n_user=Db::name('order_house')->where($u_time)->where(['admin_id'=>create_id($data['token'])])->count();//今日预约数量

        $count = Db::name('order_house')
            ->where($where)
            ->alias('a')
            ->join('house_keeper b','a.keeper_id=b.id')
            ->count();

        $i = Db::name('order_house')
            ->where($where)
            ->alias('a')
            ->join('house_keeper b','a.keeper_id=b.id')
            ->field('a.*,b.tel,b.name,b.sex')
            ->order('create_time desc')
            ->page($page, 10)
            ->select();
//var_dump($count,$i);exit;
        foreach ($i as $k=>$v){
            if($v['type']==1){
                $housing=Db::name('housing_information')
                    ->alias('a')
                    ->where(['a.housing_id'=>$v['house_id']])
                    ->join('admin_user b','a.h_agent=b.admin_id')
                    ->field('a.h_tung_num,a.h_unit_num,a.h_room_number,a.h_agent,b.name')
                    ->find();
                $i[$k]['unit']=$housing['h_tung_num'].'-'.$housing['h_unit_num'].'-'.$housing['h_room_number'];
                $i[$k]['agent']=$housing['name'];

            }else{
                $housing=Db::name('shops')
                    ->alias('a')
                    ->join('admin_user b','a.s_agent=b.admin_id')
                    ->where(['a.shops_id'=>$v['house_id']])
                    ->field('a.s_tung_num,a.s_unit_num,a.s_room_number,a.s_agent,b.name')
                    ->find();
                //var_dump($housing);exit;
                $i[$k]['unit']=$housing['s_tung_num'].'-'.$housing['s_unit_num'].'-'.$housing['s_room_number'];
                $i[$k]['agent']=$housing['name'];
            }

        }
        $arr['user_count']=$user;
        $arr['n_user']=$n_user;
        $arr['count']=$count;
        $arr['data']=$i;
        return $arr;
    }

    /**
     * 根据房源id和类型找到最新合同
     * @param $house_id
     * @param $type
     * @return array|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function contratHouse($house_id, $type) {
        $where['h_id'] = $house_id;
        $where['h_type'] = $type;
        $data = Db::name('contracted_housing')
            ->where($where)
            ->order('c_h_id desc')
            ->find();
        return $data;
    }

    /**
     * @param $id
     * @return array|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function detail($id) {
        $where['c_id'] = $id;
        $data = Db::name('contract_management')
            ->where($where)
            ->find();
        return $data;
    }
    /**
     * 预约看房确认
     * @return \think\response\Json
     */
    public function reservationConfirmation($data){
        $id=isset($data['id']) ? trim($data['id']) : '';
        if($id!=null){
            $where['id'] = array('eq',$id);
        }else{
            return false;
        }
        $date['admin_status']=2;
        $date['deal_time']=time();
        $count = Db::name('order_house')
            ->where($where)
            ->update($date);
        return $count;
    }

    /**
     * @param $house_id
     * @param $type
     * @return array|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function HouseTenantInfo($house_id, $type) {
        $data = Db::name('contracted_housing')
            ->alias('c')
            ->field('m.tenant_id, m.tenant_name, m.tenant_tel')
            ->where('c.h_id', $house_id)
            ->where('c.h_type', $type)
            ->join('tenant_contract t', 'c.c_c_mid=t.t_c_mid')
            ->join('tenant_management m', 't.t_id=m.tenant_id')
            ->order('c.c_h_id desc')
            ->find();
        return $data;
    }

    /**
     * @param $house_id
     * @param $type
     * @return array|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function ContractTenantInfo($contract_id) {
        $data = Db::name('contracted_housing')
            ->alias('c')
            ->field('m.tenant_id, m.tenant_name, m.tenant_tel')
            ->where('c.c_c_mid', $contract_id)
            ->join('tenant_contract t', 'c.c_c_mid=t.t_c_mid')
            ->join('tenant_management m', 't.t_id=m.tenant_id')
            ->order('c.h_id desc')
            ->find();
        return $data;
    }

    /**
     * 根据用户手机号获取租客和入住者信息
     * @param $tel 用户手机号
     * @return array|false|\PDOStatement|string|Model
     */
    public function user_tel($tel){

        $create_id=create_id( $tel['token']);
        $data= Db::name('tenant_management')->where(['tenant_tel'=>$tel['tel']])->where(['create_id'=>$create_id])->find();
        if($data==null){
            $data= Db::name('resident_users')->where(['resident_tel'=>$tel['tel']])->find();
        }
        return $data;

    }
}